﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using F2S.LINQ2LinkedIn.Model;
using F2S.OAuth;

namespace F2S.LINQ2LinkedIn.WinRT
{
    public class LinkedInFacade
    {
        private string _requestToken;
        private string _userSecret;
        private string _consumerKey;
        private string _consumerSecret;

        private T deserialize<T>(string data) where T : class
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(data))
            {
                var o = serializer.Deserialize(tr) as T;
                return o;
            }
        }

        public LinkedInFacade(string requestToken, string userSecret, string consumerKey, string consumerSecret)
        {
            _requestToken = requestToken;
            _userSecret = userSecret;
            _consumerKey = consumerKey;
            _consumerSecret = consumerSecret;
        }

        async public Task<Person> getPerson()
        {
            var oauth = new OAuthBase(_requestToken, _userSecret, _consumerKey, _consumerSecret);
            var r = await oauth.execute("http://api.linkedin.com/v1/people/~", "GET");

            var person = deserialize<Person>(await r.Content.ReadAsStringAsync());

            return person;
        }

        async public Task<ConnectionsCollection> getConnections()
        {
            var oauth = new OAuthBase(_requestToken, _userSecret, _consumerKey, _consumerSecret);
            var r = await oauth.execute("http://api.linkedin.com/v1/people/~/network/updates", "GET");
            var connections = deserialize<ConnectionsCollection>(await r.Content.ReadAsStringAsync());
            return connections;
        }

        async internal Task<string> getCompanies()
        {
            var oauth = new OAuthBase(_requestToken, _userSecret, _consumerKey, _consumerSecret);
            var r = await oauth.execute("http://api.linkedin.com/v1/company-search", "GET");
            return await r.Content.ReadAsStringAsync();
        }

        async internal Task<string> getNetworkUpdates()
        {
            return null;
        }
    }
}
